<?php
declare(strict_types=1);
namespace app\api\service;

use app\api\service\auth\Adapter;
use app\common\model\Third;
use app\common\model\User;
use app\common\model\UserToken;
use app\common\service\AuthService;


class ApiAuthService extends AuthService
{
    protected $allowFields = ['id', 'nickname', 'mobile', 'avatar', 'balance', 'score'];
    private Adapter $adapter;

    public function userinfo(bool $allinfo = false)
    {
        $user=$this->adapter->userinfo();
        if(!$user){
            return false;
        }
        if($allinfo){
            return $user;
        }else{
            return array_intersect_key($user,array_flip($this->allowFields));
        }
    }

    public function logout()
    {
        $this->adapter->logout();
    }

    public function getToken()
    {
        $usertoken=$this->adapter->getUserToken();
        return $usertoken->token;
    }

    public function login(string $username, string $password)
    {
        $token=uuid();
        $user=User::where('username',$username)->find();
        if(!$user){
            throw new \Exception('账号或密码错误');
        }
        if($user->password!=md5(md5($password.$user->salt))){
            throw new \Exception('账号或密码错误');
        }
        if($user->status!='normal'){
            throw new \Exception('账号已经被禁用');
        }
        $this->adapter->login($token,$user);
        $this->login_user=$this->adapter->userinfo();
    }

    public function loginByMobile(string $mobile, string $code)
    {
        // TODO: Implement loginByMobile() method.
    }

    public function loginByThirdPlatform(string $platform,Third $third)
    {
        $token=uuid();
        $user=User::find($third->user_id);
        if(!$user){
            throw new \Exception('账号不存在');
        }
        if($user->status!='normal'){
            throw new \Exception('账号已经被禁用');
        }
        $this->adapter->login($token,$user);
        $this->login_user=$this->adapter->userinfo();
    }

    public function updateToken(array $arr)
    {
        $usertoken=$this->adapter->getUserToken();
        UserToken::where('id',$usertoken->id)->update($arr);
    }

}